var express = require('express');
var router = express.Router();
var fs = require('fs');
var path = require('path');
var formidable = require('formidable')
var http = require('http'),
  util = require('util'),
  os = require('os')
var hat = require('hat')
var rack = hat.rack()
var mongoose = require('mongoose')
var connectDB = require('../connectdb')
var user = require('../schema/user')
var trend = require('../schema/trend')
var comment = require('../schema/comment')
var feedback = require('../schema/feedback')
var version = require('../schema/version')
var topic = require('../schema/topic')
var topicComment = require('../schema/topiccomment')
var middlewares = require('./middlewares');

// connectDB(mongoose)
/* GET home page. */
router.save = function (req, res, next) {
  // trend.findOne({'created':1489329988339}).populate('fromId').exec(function(err,docs){
  //   if (err) console.log(err)
  //   res.json(docs)
  // })

  // user.findOne({'created':1489331925866}).populate('trends').exec(function(err,docs){
  //   if (err) console.log(err)
  //   res.json(docs)
  // })

  // console.log(req.headers.token)
  var model = user(req.body)
  model.save(function (err, doc) {
    if (err) throw err;
    // console.log(doc)
    res.send('Succeed')
  })
}

router.loadTrend = function (req, res) {
  // trend.find({}, function (err, docs) {
  //   if (err) console.log(err)
  //   res.json(docs)
  // })
  var curPage = req.query.curPage

  trend.find({}, function (err, docs) {
    if (err) console.log(err)
    res.json(docs)
  }).sort({ 'created': -1 }).skip(10 * curPage).limit(10).populate('fromId').exec()
}


router.uploadTrend = function (req, res) {

  var form = new formidable.IncomingForm();
  form.uploadDir = path.join(__dirname, '../public/tmp');   //文件保存在系统临时目录
  form.maxFieldsSize = 1 * 1024 * 1024;  //上传文件大小限制为最大1M  
  form.keepExtensions = true;        //使用文件的原扩展名

  var targetDir = path.join(__dirname, '../public/upload');
  // 检查目标目录，不存在则创建
  fs.access(targetDir, function (err) {
    if (err) {
      fs.mkdirSync(targetDir);
    }
    middlewares.imageParse(req, form, targetDir, function (fields) {
      fields.created = new Date().getTime()
      var model = trend(fields)
      model.save(function (err, trend) {
        user.updateOne({ '_id': fields.fromId }, { $push: { 'trends': trend._id } }, function (err, result) {
          if (result == null) {
            res.send({ status: false, msg: '上传失败，内部原因' })
          } else {
            res.send({ status: true, msg: '上传成功' })
          }
        })
      })
    })
  });
}

router.checkUser = function (req, res) {

  var form = new formidable.IncomingForm();
  form.uploadDir = path.join(__dirname, '../public/tmp');   //文件保存在系统临时目录
  form.maxFieldsSize = 1 * 1024 * 1024;  //上传文件大小限制为最大1M  
  form.keepExtensions = true;        //使用文件的原扩展名

  var targetDir = path.join(__dirname, '../public/upload');
  // 检查目标目录，不存在则创建
  fs.access(targetDir, function (err) {
    if (err) {
      fs.mkdirSync(targetDir);
    }
    middlewares.imageParse(req, form, targetDir, function (fields) {
      
      user.findOneAndUpdate({ '_id': fields._id }, { $set: { 'avatar': fields.urls[0], 'name': fields.name, 'motto': fields.motto, 'gender': parseInt(fields.gender) } }, function (err, uu) {
        if (err) console.log(err)

        user.findOne({ '_id': uu._id }, function (err, u) {
          res.json(u);
        })

      })
    })
  });
}

router.pubComment = function (req, res) {
  var token = req.headers.token
  var fromId = req.query.fromId
  var model = comment(req.body)
  model.fromId = fromId
  model.created = new Date().getTime()

  user.findOne({ 'token': token }, function (err, doc) {
    if (err) console.log(err)

    if (doc == null) {
      res.json({ 'auth': false, 'data': doc })
    } else {
      model.save(function (err, doc) {
        if (err) console.log(err)
        res.json({ 'auth': true, 'data': [] })
      })
    }
  })

}

router.getComments = function (req, res) {
  var toId = req.query.toId
  comment.find({ 'toId': toId }).sort({ 'created': -1 }).populate('fromId').exec(function (err, comments) {
    if (err) console.log(err)
    res.json(comments)
  })
}

router.register = function (req, res) {

  var model = user(req.body)

  user.findOne({ 'account': req.body.account }, function (err, doc) {
    if (err) console.log(err)
    if (doc == null) {
      model.save(function (err, user) {
        if (err) console.log(err)
        // res.json(user)
        login(user.token, res)
      })
    } else {
      res.json({ err: 0, msg: '用户已存在' })
    }
  })
}

/**
 * @param {string} token 身份验证 
 * @param {object} res response 
 */
var login = function (token, res) {
  var newToken = rack()
  user.updateOne({ 'token': token }, { token: newToken }, function (err, doc) {
    if (err) console.log(err)
    if (doc == null) {

      res.json({ result: 0, status: '登录失败,未找到' }) //未找到
    } else {
      user.findOne({ 'token': newToken }, function (err, u) {
        if (err) console.log(err)
        res.json(u)
      })

    }
  })
}

router.loginForAP = function (req, res) {
  var token = rack()

  user.findOneAndUpdate({ account: req.body.account, password: req.body.password }, { token: token }, function (err, doc) {
    if (doc == null) { //未找到该账号
      res.json({ status: false, msg: '未找到该用户' })
    } else {
      doc.token = token;
      res.json({ status: true, msg: '登录成功', user: doc })
    }
  })
}

router.loginForQQ = function (req, res) {
  var account = req.body.account;
  var model = user(req.body)
  user.findOne({ 'account': account }, function (err, doc) {
    if (err) console.log(err)
    if (doc == null) {
      model.save(function (err, user) {
        if (err) console.log(err)
        res.json(user)
      })
    } else {
      var newToken = rack()
      user.updateOne({ 'account': account }, { 'token': newToken }, function (err) {
        doc.token = newToken;
        res.json(doc)
      })
    }
  })
}

router.like = function (req, res) {
  var userId = req.query.userId
  var trendId = req.query.trendId
  trend.findOne({ '_id': trendId }, function (err, t) {
    if (err) console.log(err)
    if (t.likeIds.indexOf(userId) == 0) {
      trend.updateOne({ '_id': trendId }, { $pull: { 'likeIds': userId }, $inc: { 'likes': -1 } }, function (err, doc) {
        if (err) console.log(err)
        res.json(doc)
      })
    } else {
      trend.updateOne({ '_id': trendId }, { $push: { 'likeIds': userId }, $inc: { 'likes': 1 } }, function (err, doc) {
        if (err) console.log(err)
        res.json(doc)
      })
    }
  })
}
router.getToday = function (req, res) {
  var end = new Date().getTime()
  var mSecond = 24 * 3600 * 1000
  var start = end - end % mSecond

  trend.find({ created: { $gte: start, $lte: end } }, function (err, docs) {
    if (err) console.log(err)
    res.json(docs)
  }).sort({ 'likes': -1 }).limit(10).populate('fromId').exec()
}

router.getWeekend = function (req, res) {
  var end = new Date().getTime()
  var mSecond = 24 * 3600 * 1000 * 7
  var start = end - end % mSecond
  trend.find({ created: { $gte: start, $lte: end } }, function (err, docs) {
    if (err) console.log(err)
    res.json(docs)
  }).sort({ 'likes': -1 }).limit(10).populate('fromId').exec()
}

router.getMonth = function (req, res) {
  var end = new Date().getTime()
  var date = new Date().getDate()
  var mSecond = 24 * 3600 * 1000
  var days = Math.floor(end / mSecond)
  var start = (days - date + 1) * mSecond

  trend.find({ created: { $gte: start, $lte: end } }, function (err, docs) {
    if (err) console.log(err)
    res.json(docs)
  }).sort({ 'likes': -1 }).limit(10).populate('fromId').exec()
}


router.getMyTrend = function (req, res) {
  var userId = req.query.userId
  trend.find({ 'fromId': userId }, function (err, docs) {
    if (err) console.log(err)
    res.json(docs)
  }).sort({ 'created': -1 }).populate('fromId').exec()
}

router.commitFeedback = function (req, res) {
  var feedbackModel = feedback(req.body);
  feedbackModel.save(function (err, doc) {
    if (err) console.log(err)
    res.json('反馈成功')
  })
}

router.uploadVersion = function (req, res) {
  var model = version(req.body)
  model.created = new Date().getTime()
  model.save(function (err, version) {
    if (err) console.log(err)
    res.json(version)
  })
}

router.getVersion = function (req, res) {
  version.findOne(function (err, version) {
    if (err) console.log(err)
    res.json(version)
  }).sort({ 'created': -1 })
}

router.getTopics = function (req, res) {
  topic.find({}, function (err, topics) {
    if (err) console.log(err)
    res.json(topics)
  }).limit(25)
}

router.pubTopic = function (req, res) {
  var model = topic(req.body)
  model.save(function (err, topic) {
    if (err) console.log(err)
    res.json(topic)
  })
}

router.getTopicComment = function (req, res) {
  var topicId = req.query.topicId
  topicComment.find({ 'topicId': topicId }).sort({ 'created': -1 }).populate(['fromId', 'toId']).exec(function (err, comments) {
    if (err) console.log(err)
    res.json(comments)
  })
}

router.pubTopicComment = function (req, res) {
  // var model = topicComment(req.body)
  // model.save(function (err, topicComment) {
  //   if (err) console.log(err)
  //   res.json(topicComment)
  // })

  var token = req.headers.token
  var fromId = req.query.fromId
  var model = topicComment(req.body)
  model.fromId = fromId
  model.created = new Date().getTime()

  user.findOne({ 'token': token }, function (err, doc) {
    if (err) console.log(err)

    if (doc == null) {
      res.json({ 'auth': false, 'data': doc })
    } else {
      model.save(function (err, doc) {
        if (err) console.log(err)
        res.json({ 'auth': true, 'data': [] })
      })
    }
  })
}

router.uploadFile = function (req, res) {
  var form = new formidable.IncomingForm();
  form.uploadDir = path.join(__dirname, '../public/tmp');   //文件保存在系统临时目录
  form.keepExtensions = true;        //使用文件的原扩展名

  var targetDir = path.join(__dirname, '../public/audio');
  // 检查目标目录，不存在则创建
  fs.access(targetDir, function (err) {
    if (err) {
      fs.mkdirSync(targetDir);
    }

    middlewares.fileParse(req, form, targetDir, function (fields) {
      fields.created = new Date().getTime();
      var model = trend(fields)
      model.save(function (err, doc) {
        if (err) console.log(err)
        res.json({ status: true, msg: '上传成功', user: doc } )
      })
    })
  })
}

router.getAllImage = function(req,res){
  var curPage = req.query.curPage

  trend.find({'type':0}, function (err, docs) {
    if (err) console.log(err)
    res.json(docs)
  }).sort({ 'created': -1 }).skip(10 * curPage).limit(10).populate('fromId').exec()
}

router.getAllMusic = function(req,res){
  var curPage = req.query.curPage

  trend.find({'type':1}, function (err, docs) {
    if (err) console.log(err)
    res.json(docs)
  }).sort({ 'created': -1 }).skip(10 * curPage).limit(10).populate('fromId').exec()
}

router.getAllVideo = function(req,res){
  var curPage = req.query.curPage

  trend.find({'type':2}, function (err, docs) {
    if (err) console.log(err)
    res.json(docs)
  }).sort({ 'created': -1 }).skip(10 * curPage).limit(10).populate('fromId').exec()
}

router.getBestVideo = function(req,res){
  trend.find({'type':2}, function (err, docs) {
    if (err) console.log(err)
    res.json(docs)
  }).sort({ 'likes': -1 }).limit(10).populate('fromId').exec()
}

router.getBestMusic = function(req,res){
  trend.find({'type':1}, function (err, docs) {
    if (err) console.log(err)
    res.json(docs)
  }).sort({ 'likes': -1 }).limit(10).populate('fromId').exec()
}

router.getBestImage = function(req,res){
  trend.find({'type':0}, function (err, docs) {
    if (err) console.log(err)
    res.json(docs)
  }).sort({ 'likes': -1 }).limit(10).populate('fromId').exec()
}






module.exports = router;
